package com.sumainfor.pc.cfo.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Sets;
import com.sumainfor.common.exception.TCException;
import com.sumainfor.common.util.ContextUtils;
import com.sumainfor.common.util.CustomMap;
import com.sumainfor.common.util.DateUtils;
import com.sumainfor.common.util.JsonResult;
import com.sumainfor.common.utlis.ParamsCommon;
import com.sumainfor.pc.cfo.dao.InvoiceAuditMapper;
import com.sumainfor.pc.cfo.feign.BaseTenantFeign;
import com.sumainfor.pc.cfo.feign.BaseZullFeign;
import com.sumainfor.pc.cfo.service.InvoiceAuditService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Eddy Chen
 * @since 2019-05-05
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class InvoiceAuditServiceImpl implements InvoiceAuditService {

    @Autowired
    private InvoiceAuditMapper mapper;

    @Autowired
    private BaseTenantFeign tenantFeign;

    @Autowired
    private BaseZullFeign zullFeign;

    /**
     * 查询表格的数据
     *
     * @param page
     * @param params InvoType: 发票类型
     *               0:专票
     *               1:普票
     * @return
     */
    @Override
    public JsonResult getTableList(Page page, Map<String, Object> params) {
        //获取搜索的条件
        String search = MapUtils.getString(params, "search");
        if (StringUtils.isNotBlank(search)) {
            //搜索租客信息
            List<Map<String, Object>> searchList = tenantFeign.getUserInfoListByLikeSelect(search);
            if (CollectionUtils.isEmpty(searchList)) {
                return JsonResult.success(page);
            }
            //不为空查询
            params.put("ids", searchList.stream().map(item -> MapUtils.getString(item, "TenId")).collect(Collectors.toList()));
        }

        IPage<Map<String, Object>> dataList = mapper.selectTableList(page, params);
        Set<String> tenIdList = Sets.newHashSet();
        dataList.setRecords(dataList.getRecords().stream().map(dat -> {
//            CustomMap map = CustomMap.create();
            Integer type = MapUtils.getInteger(dat, "InvoType");
            if (Objects.equals(type, 0)) {
                dat.put("InvoType", "增值税专用发票");
            } else if (Objects.equals(type, 1)) {
                dat.put("InvoType", "增值税普通发票（公司）");
            } else {
                dat.put("InvoType", "增值税普通发票（个人）");
            }
//            map.put("InvoId", dat.get("InvoId"));
//            map.put("SouType", dat.get("SouType"));
//            map.put("ApplyType", dat.get("ApplyType"));
//            map.put("ApplyId", dat.get("ApplyId"));
//            map.put("ApplyName", dat.get("ApplyName"));
//            map.put("ApplyIDcard", dat.get("ApplyIDcard"));
//            map.put("ComName", dat.get("ComName"));
//            map.put("TaxNumber", dat.get("TaxNumber"));
//            map.put("ComAddress", dat.get("ComAddress"));
//            map.put("Belongsbank", dat.get("Belongsbank"));
//            map.put("Banknumber", dat.get("Banknumber"));
//            map.put("TotalAmount", dat.get("TotalAmount"));
//            map.put("ApplyTime", dat.get("ApplyTime"));
//            map.put("Operating", dat.get("Operating"));
//            map.put("Status", dat.get("Status"));
            dat.put("Picture", MapUtils.getString(dat, "InService", "").split(","));

            //查询关联账单信息
            List<Map<String, Object>> infoList = mapper.selectInvoiceInfo(MapUtils.getString(dat, "InvoId"));
            dat.put("infoList", infoList);
            //查询开票人ID
            String sysUserId = MapUtils.getString(dat, "SysUserId");
            if (StringUtils.isNotBlank(sysUserId)) {
                JsonResult<List<Map<String, Object>>> userInfo = zullFeign.getUserInfo(Arrays.asList(sysUserId));
                if (!userInfo.isSuccess()) {
                    throw new TCException(userInfo.getErrorMessage());
                }
                List<Map<String, Object>> result = userInfo.getResult();
                if (!CollectionUtils.isEmpty(result)) {
                    dat.put("AuditUserName", result.get(0).get("username"));
                }
            }

            DateUtils.formatDateByMap(dat, "yyyy年MM月dd日 HH:mm");
            tenIdList.add(MapUtils.getString(dat, "ApplyId"));
            return dat;
        }).collect(Collectors.toList()));

        if (CollectionUtils.isNotEmpty(tenIdList)) {
            List<Map<String, Object>> list = tenantFeign.selectTenantInfoByIdList(tenIdList);
            if (CollectionUtils.isNotEmpty(list)) {
                for (Map<String, Object> map : list) {
                    for (Map<String, Object> objectMap : dataList.getRecords()) {
                        if (Objects.equals(objectMap.get("ApplyId"), map.get("TenId"))) {
                            objectMap.putAll(map);
                        }
                    }
                }
            } else {
                return JsonResult.error("租客端服务器繁忙.....");
            }
        }

        return JsonResult.success(dataList);
    }


    /**
     * 确认开票
     *
     * @param invoiceId
     * @return
     */
    @Override
    public JsonResult affirm(String invoiceId) {
        int row = mapper.updateInvoice(ParamsCommon.commonUpdateParms(CustomMap.create("InvoId", invoiceId)
                        .put("SysUserId", ContextUtils.getUserId())
                        .put("Operating", new Date())
                        .put("Status", 1)
                , getClass()));
        return row <= 0 ? JsonResult.actionFailure() : JsonResult.actionSuccess();
    }

    /**
     * 驳回开票申请
     * @param invoiceId
     * @return
     */
    @Override
    public JsonResult reject(String invoiceId) {
        int row = mapper.updateInvoice(ParamsCommon.commonUpdateParms(CustomMap.create("InvoId", invoiceId)
                        .put("SysUserId", ContextUtils.getUserId())
                        .put("Status", 2)
                , getClass()));
        return row <= 0 ? JsonResult.actionFailure() : JsonResult.actionSuccess();
    }

}
